package org.amos.filestorage.platform.s3;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.upyun.RestManager;
import com.upyun.UpException;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.amos.filestorage.exception.FileStorageException;
import org.amos.filestorage.platform.AbstractFilePlatform;
import org.amos.filestorage.platform.config.s3.UpyunFilePlatformConfig;
import org.junit.internal.Throwables;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.function.Consumer;

/**
 * 又拍云 USS 存储
 */
public class UpyunFilePlatform extends AbstractFilePlatform<UpyunFilePlatformConfig> {


    private RestManager client;

    public UpyunFilePlatform(String id, UpyunFilePlatformConfig config) {
        super(id, config);
    }

    @Override
    public void initClient() {
        client = new RestManager(config.getBucket(), config.getAccessKey(), config.getSecretKey());
    }

    @Override
    public String upload(byte[] bytes, String path, String type) {
        try {
            HashMap<String, String> params = new HashMap<>();
            params.put(RestManager.PARAMS.CONTENT_TYPE.getValue(), type);
            try (Response result = client.writeFile(path, new ByteArrayInputStream(bytes), params)) {
                if (!result.isSuccessful()) {
                    throw new UpException(result.toString());
                }
            }
            return StrUtil.format("{}/{}", config.getDomain(), path);
        } catch (IOException | UpException e) {
            throw new FileStorageException(Throwables.getStacktrace(e));
        }
    }

    @Override
    public Boolean delete(String path) {
        try (Response ignored2 = client.deleteFile(path, null)) {
            return Boolean.TRUE;
        } catch (IOException | UpException e) {
            throw new FileStorageException(Throwables.getStacktrace(e));
        }
    }

    @Override
    public Boolean exists(String path) {
        try (Response response = client.getFileInfo(path)) {
            return StrUtil.isNotBlank(response.header("x-upyun-file-size"));
        } catch (IOException | UpException e) {
            throw new FileStorageException("判断文件是否存在失败！", e);
        }
    }

    @Override
    public void download(String path, Consumer<InputStream> consumer) {
        try (Response response = client.readFile(path);
             ResponseBody body = response.body();
             InputStream in = body == null ? null : body.byteStream()) {
            if (body == null) {
                throw new FileStorageException("文件下载失败，结果为 null ！String path：" + path);
            }
            if (!response.isSuccessful()) {
                throw new UpException(IoUtil.read(in, StandardCharsets.UTF_8));
            }
            consumer.accept(in);
        } catch (IOException | UpException e) {
            throw new FileStorageException(org.junit.internal.Throwables.getStacktrace(e));
        }
    }
}
